﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;

namespace Nirvana
{
    [AddComponentMenu("Nirvana/UI/Bind/Variable Bind Attach")]
    [RequireComponent(typeof(GameObjectAttach))]
    public class UIVariableBindAttach : UIVariableBind
    {
        private static Logger logger = LogSystem.GetLogger("UIVariableBindAttach");
        [SerializeField]
        [VariableName(UIVariableType.Asset)]
        private string assetBind;
        private GameObjectAttach _objattach;
        private UIVariable _uivariable;

        protected override void BindVariables()
        {
            Assert.IsNull<UIVariable>(this._uivariable);
            if (!string.IsNullOrEmpty(this.assetBind))
            {
                this._uivariable = base.FindVariable(this.assetBind);
                if (this._uivariable == null)
                {
                    UIVariableBindAttach.logger.LogWarning("{0} can not find a variable {1}", new object[]
                    {
                        base.name,
                        this.assetBind
                    });
                }
                else
                {
                    this._uivariable.OnValueInitialized += this.OnValueInitialized;
                    this._uivariable.OnValueChanged += this.OnValueInitialized;
                    this._uivariable.Add(this);
                    this.OnValueInitialized();
                }
            }
        }
        protected override void UnbindVariables()
        {
            if (this._uivariable != null)
            {
                this._uivariable.OnValueInitialized -= this.OnValueInitialized;
                this._uivariable.OnValueChanged -= this.OnValueInitialized;
                this._uivariable.Remove(this);
                this._uivariable = null;
            }
        }

        private void OnValueInitialized()
        {
            if (this._objattach == null)
            {
                this._objattach = base.GetComponent<GameObjectAttach>();
            }
            if (this._objattach != null)
            {
                AssetID asset = this._uivariable.GetAsset();
                this._objattach.AssetId = asset;
            }
        }

    }
}

